<html>
  <head>
      <script src='/_ah/channel/jsapi'></script>
      <style type='text/css'>
        div {
          overflow: hidden;
        }

        #wcs-iframe {
          display: none;
        }

        #question-area {
          display: none;
          margin-right: 8px;
        }

        #response-panel {
          display: none;
        }

        #interaction-area {
          float: left;
          width: 425px;
          height: 100%;
          border-right: 1px solid lightGrey;
        }

        #scoreboard {
          float: right;
          width: 225px;
        }

        #activity-stream {
          width: 100%;
        }

        #display-area {
          margin: auto;
          width: 700px;
          height: 500px;
        }

        #question-padding, #response-padding {
          margin: 8px;
        }

        #quiz-done {
          background: #FFF1A8;
          display: none;
          align: center;
          padding: 8px;
        }

        .stats-heading {
          font-weight: bold;
          padding-bottom: 8px;
        }

        .ui-panel {
          background: #E0ECFF;
          padding: 10px;
          margin: 10px;
          height: 200px;
        }

        .question {
          padding: 4px;
        }

        #activity {
          font-size: 12px;
        }

        .activity-question-text {
          font-style: italic;
        }

        .result-c {
          color: #008A35;
        }

        .result-w {
          color: #FF0000;
        }
        
        #scores {
          font-size: 12px;
        }

        .score-name {
          float: left;
          width: 100px;
          height: 16px;
        }
        
        .score-value {
          float: right;
          width: 80px;
        }
        
        .correct-blip {
          background: #008A35;
          width: 2px;
          height: 12px;
          float: left;
          border: 1px solid black;
        }

        .incorrect-blip {
          background: #FF0000;
          width: 2px;
          height: 12px;
          float: left;
          border: 1px solid black;
        }
        
        .empty-blip {
          background: #000000;
          width: 2px;
          height: 12px;
          float: left;
          border: 1px solid black;
        }

        body {
          font-family: arial, sans-serif;
        }
      </style>
  </head>
  <body>
    <script type='text/javascript'>
      var MAX_STATUS_ITEMS = 8;

      var activityStream = [];
      var userScores = [];
      var currentQuestionId = 0;
      var scores = {};
      var connected;
      var hasResult = false;
      var complete = false;
      var hasQuestion = false;
      var signedIn = false;

      htmlEscape = function(s) {
        return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
      }

      setVisiblePanels = function() {
        var elements = {
          'signin-area' : 'none',
          'response-panel' : 'none',
          'continue-button' : 'none',
          'question-area' : 'none',
          'quiz-done' : 'none',
          'waiting' : 'none'
        }

        if (!signedIn) {
          elements['signin-area'] = 'block';
        } else {
          if (complete) {
            elements['quiz-done'] = 'block';
          }

          if (hasResult) {
            elements['response-panel'] = 'block';
            if (!complete) {
              elements['continue-button'] = 'block';
            }
          } else if (hasQuestion) {
            elements['question-area'] = 'block';
          } else {
            elements['waiting'] = 'block';
          }
        }

        for (var name in elements) {
          document.getElementById(name).style.display = elements[name];
        }
      }

      setName = function() {
        signedIn = true;  
        var name = encodeURIComponent(document.getElementById('name').value);
        sendMessage('/setname?n=' + name)
        setVisiblePanels()
      }

      showComplete = function() {
        complete = true;
      }

      showResult = function(result) {
        hasResult = true;
        document.getElementById('result-area').innerHTML = 
          result.c ? 
            "You are correct!" : 
            "Sorry, that's incorrect. The correct answer is: <b>" + htmlEscape(result.a) + "</b>";
      }

      setCurrentQuestion = function(question) {
        complete = false;
        hasQuestion = true;

        document.getElementById('question-text').innerHTML = question.q;
        currentQuestionId = question.id;
        for (var i = 0; i < question.a.length; i++) {
          var s = 'answer-text-' + i;
          document.getElementById(s).innerHTML = question.a[i];

          s = 'answer-' + i;
          document.getElementById(s).checked = false;    
    	  }
      }

      logActivity = function(response) {
        if (activityStream.length >= MAX_STATUS_ITEMS) {
          activityStream.shift();
        }
        activityStream.push(response);

        innerHTML = "";
        for (i = activityStream.length - 1; i >= 0; i--) {
          var activity = activityStream[i];
          switch (activity.type) {
            case 'r':
              result = "<div class='activity-item'>"
              result += "<span class='activity-user-name'>" + htmlEscape(activity.u) + "</span>";
              result += " <span class='result-";
              result += activity.r ? "c'>correctly</span>" : "w'>incorrectly</span>";
              result += " answered '<span class='activity-question-text'>" + activity.q + ".</span>'";
              result += "</div>";
              break;
            case 'j':
              result = "<div class='join'>" + htmlEscape(activity.u) + " joined.</div>";
              break;

          }
          innerHTML += result;
        }
        document.getElementById('activity').innerHTML = innerHTML;
      }

      updateScoreboard = function(scoreboard) {
        var innerHTML = "";
        for (var i = 0; i < Math.min(scoreboard.length, MAX_STATUS_ITEMS - 1); i++) {
          var item = "<div class='score-" + i % 2 + "'>";
          item += "<span class='score-name'>" + htmlEscape(scoreboard[i].u) + "</span>"
          item += "<span class='score-value'>";
          for (var j = 0; j < scoreboard[i].s; j++) {
            item += "<span class='correct-blip'></span>"
          }
          for (; j < scoreboard[i].t; j++) {
            item += "<span class='incorrect-blip'></span>"
          }
          for (; j < 19; j++) {
            item += "<span class='empty-blip'></span>"
          }
          item += "</span>";
          item += "</div>"
          innerHTML += item;
        }
        document.getElementById('scores').innerHTML = innerHTML;
      }

      buttonPressed = function(id) {
        var text = document.getElementById('answer-text-' + id).innerHTML;
        sendMessage('/answer?a=' + text + '&q=' + currentQuestionId);
      }

      continueButtonPressed = function() {
        hasResult = false;

        document.getElementById('response-panel').style.display = 'none';
        document.getElementById('question-area').style.display = 'block';
      }

      startOverButtonPressed = function() {
        hasResult = false;
        sendMessage('/startover')
      }

      sendMessage = function(path) {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', path, true);
        xhr.send();
      }

      var token = '{{ channel_id }}';

      var channel = new goog.appengine.Channel(token);
      var socket = channel.open();
      socket.onopen = function() {
        window.setTimeout(function() {sendMessage('connected')}, 100);
      }
      socket.onmessage = function(evt) {
          var o = JSON.parse(evt.data);

          if (o.c) {
            showComplete();
          }

          if (o.r) {
            showResult(o.r);
          }

          if (o.q) {
            setCurrentQuestion(o.q);
          }

          if (o.a) {
            logActivity(o.a);
          }

          if (o.s) {
            updateScoreboard(o.s);
          }

          setVisiblePanels();
        }

        window.setTimeout(function() {socket.onmessage({data : '{{ initial_messages }}'})}, 500);
    </script>
    <div id='display-area'>
    <h2>The Google IO Trivia Quiz</h2>
    <div id='top-panel' class='ui-panel'>
      <div id='interaction-area'>
        <div id='signin-area'>
          <h4>Welcome, {{ nickname }}!</h4>
          Please enter your name as you'd like others to see it:
          <input id='name' type='text' value='{{ nickname }}'>
          <br>
          <a href='#' onclick='setName()'>continue to game...</a>
        </div>
        <div id='question-area'>
          <span id='question-text'>Connecting</span>
          <div id='question-padding'></div>
          <div id='questions'>
            <div class='question'>
              <input type='radio' name='answers' id='answer-0' value='0' onclick='buttonPressed(0)'>
              <label for='answer-0' id='answer-text-0'>Answer 1</label>
            </div>
            <div class='question'>
              <input type='radio' name='answers' id='answer-1' value='1' onclick='buttonPressed(1)'>
              <label for='answer-1' id='answer-text-1'>Answer 2</label>
            </div>
            <div class='question'>
              <input type='radio' name='answers' id='answer-2' value='2' onclick='buttonPressed(2)'>
              <label for='answer-2' id='answer-text-2'>Answer 3</label>
            </div>
            <div class='question'>
              <input type='radio' name='answers' id='answer-3' value='3' onclick='buttonPressed(3)'>
              <label for='answer-3' id='answer-text-3'>Answer 4</label>
            </div>
          </div>
        </div>
        <div id='response-panel'>
          <div id='result-area'>
          </div>
          <div id='response-padding'></div>
          <a href='#' onclick='continueButtonPressed()' id='continue-button'>Continue</a>
        </div>
        <div id='quiz-done'>
          You have answered all the questions on the quiz!<br>
          If you'd like to, you can <a href='#' onclick='startOverButtonPressed()'>start over</a>.
        </div>
        <div id='waiting' style='display:none'>
          Waiting for connection...
        </div>
      </div>
      <div id='scoreboard'>
        <div class='stats-heading'>
          Scores
        </div>
        <div id='scores'>
          Nobody has answered a question yet.
        </div>
      </div>
      </div>
      <div id='stats-area' class='ui-panel'>
        <div id='activity-stream'>
          <div class='stats-heading'>
            Recent Activity
          </div>
          <div id='activity'>
          </div>
        </div>
    </div>
    </div>
  </body>
</html>
